const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentDate: new Date().getTime(),
    minDate:  new Date(1949,8,31).getTime(),
    tomorrow:'',
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      if(type === 'day'){
        return `${value}日`;
      }
      return value;
    },
    incrementList:[
      {
        name: '选项1',
      },
      {
        name: '选项2',
      },
      {
        name: '选项3',
      },
    ],
    startBool:false,
    endBool:false,
    incrementBool:false,
    array:[],
    increment:null,
    indexs:0,
    startDate:'',
    endDate:'',
    budgetVal:'',
    quantityVal:'',
    serviceList:[],
    serviceShow:false,
    result:[],
    serviceChange:{},
    type:'',//1是招标任务2是悬赏任务
    // 服务数据
    serviceIdList:[],
    serviceTextList:[],
    servicePrice:'0'
  },

  incrementSelect(e){

  },

  incrementClose(){
    this.setData({
      incrementBool:false
    })
  },

  incrementBoolClick(){
    this.setData({
      incrementBool:true
    })
  },
  startBoolClick(){
    this.setData({
      startBool:true
    })
  },
  endBoolClick(){
    this.setData({
      endBool:true
    })
  },

  startHand(e){
    this.setData({
      startBool:false,
      startDate: this.formatDate(e.detail)
    })
  },

  startCancel(){
    this.setData({
      startBool:false
    })
  },

  endHand(e){
    this.setData({
      endBool:false,
      endDate: this.formatDate(e.detail)
    })
  },

  endCancel(){
    this.setData({
     endBool:false
    })
  },

  budChange(e){
    let budgetVal
    if (/^(\d?)+(\.\d{0,2})?$/.test(e.detail)) { //正则验证，提现金额小数点后不能大于两位数字
      budgetVal = e.detail;
    } else {
      budgetVal = e.detail.substring(0, e.detail.length - 1);
    }
    this.setData({
      budgetVal
    })
  },

  // 增值服务
  bindPickerChange: function (e) {
    this.setData({
      indexs: e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options,'options-----------------------------')
    this.setData({
      type: options.taskType
    })
    this.getDate()
    // 增值服务
    // this.serviceInfo();
    this.serviceList()
  },

  getDate(){
    let tomorrow = new Date().getTime()+24*60*60*1000;
    this.setData({
      tomorrow
    })
  },



  formatDate: function (value) {//调用时间戳为日期显示
    let date = new Date(value)
    let y = date.getFullYear()  //获取年份
    let m = date.getMonth() + 1  //获取月份
    m = m < 10 ? "0" + m : m  //月份不满10天显示前加0
    let d = date.getDate()  //获取日期
    d = d < 10 ? "0" + d : d  //日期不满10天显示前加0
    return y + "-" + m + "-" + d
  },


  // 增值服务
  serviceList:function(){
    var _this = this;
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.baseUrl + 'myTask/gettaskService',
      data: {
        token: app.globalData.token
      },
      success(res) {
        wx.hideLoading()
        console.log(res)
        if (res.data.code == 1000) {
          var obj = res.data.data
          _this.setData({
            serviceList:obj
          })
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },

  onChange(e) {
    this.setData({
      result: e.detail,
    });
  },

  noop(e){
    const { index ,title} = e.currentTarget.dataset;
    const {serviceChange}=this.data
    if(serviceChange[index]){
      delete serviceChange[index]
    }else {
      serviceChange[index]=title
    }
    this.setData({
      serviceChange
    })

  },

  serviceBtn(){
    const {result,serviceList}=this.data
    let servicePrice = '0';
    let serviceIdList = [];
    let serviceTextList = [];
    result.forEach(i=>{
      servicePrice = Number(servicePrice) + Number(serviceList[i].price)
      serviceIdList.push(serviceList[i].id);
      serviceTextList.push(serviceList[i].title)
    })
    this.setData({
      serviceIdList,
      serviceTextList,
      servicePrice
    })
    this.onClose()
  },

  toggle(event) {
    const { index ,title} = event.currentTarget.dataset;
    const {serviceChange}=this.data
    if(serviceChange[index]){
      delete serviceChange[index]
    }else {
      serviceChange[index]=title
    }
    this.setData({
      serviceChange
    })
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  },


  // 选择增值服务
  serviceSelect:function(){
    this.setData({
      serviceShow:true
    })
  },
  //关闭服务选择
  onClose(){
    this.setData({
      serviceShow:false
    })
  },
  // 发布任务
  releaseTask:function(){
    var {
      budgetVal,
      quantityVal,
      startDate,
      endDate,
      serviceIdList,
      servicePrice,
      serviceTextList } = this.data
    if(!budgetVal){
      wx.showToast({
        title: '请输入预算价格',
        icon: 'none',
        duration: 2000
      })
      return
    }
    serviceTextList = JSON.stringify(serviceTextList)
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
    let pageData = prevPage.data;
    var taskType = '';
    if (pageData.taskType == 1){
      taskType = 'zhaobiao'
      quantityVal=1
    }else{
      taskType = 'xuanshang'
    }

    wx.showLoading({
      title: '加载中',
    })
    var _this = this;
    JSON.stringify(serviceIdList)
    wx.request({
      url: app.globalData.baseUrl + 'myTask/createTask',
      data: {
        title: pageData.taskTitleVal,
        desc: pageData.taskDescriptionVal,
        cate_id: pageData.taskid,
        bounty: budgetVal,
        worker_num: quantityVal,
        province: pageData.id,
        city: pageData.subid,
        begin_at: startDate,
        delivery_deadline: endDate,
        status:1,
        file_id: pageData.upImgId,
        phone: pageData.contactVal,
        conference: pageData.conference,
        maincolor: pageData.maincolor,
        scene: pageData.scene,
        current_stage: pageData.surrente_stage,
        type_id: taskType,
        service_id: serviceIdList,
        task_id:'',
        token: app.globalData.token,
        teamwork:pageData.indexs
      },
      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success(res) {
        wx.hideLoading()
        console.log(res)
        if (res.data.code == 1000) {
          wx.showToast({
            title: '发布成功,待审核',
            icon: 'success',
            duration: 2000
          })
          var task_id = res.data.data.task_id
          if (res.data.data.create_order){
            var url = app.globalData.baseUrl + 'pay/orderInfo';
            // 获取订单号
            var data = {
              task_id: task_id,
              token: app.globalData.token
            }
            wx.showLoading({
              title: '正在创建订单',
            })
            app.wxGetRequest(url, data, (orderRes) => {
              console.log(orderRes)
              wx.hideLoading()
              if (orderRes.code == 1000) {
                wx.navigateTo({
                  url: '/taskPage/pages/pay/pay?servicePrice=' + servicePrice + '&title=' + pageData.taskTitleVal + '&taskid=' + task_id + '&serviceTextList=' + serviceTextList + '&code=' + orderRes.data.code,
                })
              }
            }, (err) => {
              wx.hideLoading()
              wx.showToast({
                title: err.data.message,
                icon: 'none',
                duration: 2000
              })
            })
          }else{
            setTimeout(function () {
              wx.reLaunch({
                url: '/pages/index/index',
              })
            }, 2000)
          }
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
